package belf.migrate.engine.dao;

import belf.migrate.core.util.ConfigUtil;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;

import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;

@Slf4j
public abstract class BaseDAO<T> {


    private Properties properties = new Properties();

    public BaseDAO() {

        try {
            properties.load(new FileReader(new File(ConfigUtil.getConfigDir() + File.separator + "jdbc.properties")));
            Class.forName(properties.getProperty("driver"));
        } catch (IOException e) {
            log.error("Fatal Error!!! Cannot Load File jdbc.properties error.");
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            log.error("Fatal Error!!! Cannot Load JDBC Driver: {}", properties.getProperty("driver"));
            e.printStackTrace();
        }

    }

    public abstract void save(T obj);

    public abstract T queryById(long id);

    public abstract void deleteById(long id);

    protected void executeSql(String sql) {
        Connection connection = null;
        Statement statement = null;
        try {
            connection = getConnection();
            statement = connection.createStatement();
            statement.execute(sql);
            statement.close();
            connection.close();
        } catch (SQLException e) {
            log.error("Execute sql error!!! sql: {}, message: ", sql, e.getMessage());
            e.printStackTrace();
        } finally {
            try {
                if (null != statement) {
                    statement.close();
                }
                if (null != connection) {
                    connection.close();
                }
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }

    }

    public Connection getConnection() throws SQLException {
        return DriverManager.getConnection(properties.getProperty("url"),
                properties.getProperty("user"),
                properties.getProperty("password"));
    }

}
